package com.ehi.tsconfig.service;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.apache.commons.exec.CommandLine;
import org.springframework.beans.factory.annotation.Value;

import com.ehi.tsconfig.domain.SCMConfigure;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class GitHandler implements SCMHandler {
    
    private static int DEFAULT_SUCCESS_SIGNAL = 0;
    @Value("${local.gitpath.fast-pi}")
    private String localGitPath;
    
    @Override
    public ExecuteResult createProject(SCMConfigure config) {
        // TODO Auto-generated method stub
        CommandLine cmd = new CommandLine("git");
        cmd.addArgument("clone");
        cmd.addArgument("${url}");
        Map<String, String> map = Maps.newHashMap();
        map.put("url", "https://git.ehealthinsurance.com/scm/bo/fast-pi.git");
        cmd.setSubstitutionMap(map);
        ExecuteResult result = ExecuteCmd.getInstance().exeCmd(cmd, DEFAULT_SUCCESS_SIGNAL);
        return result;
        
    }
    
    private ExecuteResult executeOne(CommandLine cmd, File workingDir) {
        ExecuteResult result = ExecuteCmd.getInstance().exeCmd(cmd, DEFAULT_SUCCESS_SIGNAL, workingDir);
        return result;
    }

    @Override
    public ExecuteResult commitProject(SCMConfigure config) {
        // TODO Auto-generated method stub
        return null;
    }
    
    public List<ExecuteResult> createNewInstance(ExecuteResult result) {
        File workingDir = new File(this.localGitPath);
        List<CommandLine> cmds = Lists.newArrayList();
        CommandLine cmd2 = CommandLine.parse("cmd /c gradle newInstance2");
        cmds.add(cmd2);
        //cmds.add(CommandLine.parse("dir"));
        return this.batchExecute(cmds,workingDir);
    }
    
    private List<ExecuteResult> batchExecute(List<CommandLine> cmds, File workingDir) {
        List<ExecuteResult> results = Lists.newArrayList();
        cmds.stream().forEach(cmd -> {
            ExecuteResult result = this.executeOne(cmd, workingDir);
            results.add(result);
        });
        return results; 
    }

}
